import $ from "jquery";
import L from "leaflet";
import chun from "../../../../stores/chun.js";
/**台风对象 */
let Typhoon = function () {
  /**地图对象 */
  this.map = null;
  /**台风查询接口 */
  // this.typhoonQueryUrlFourCreat = "https://www.oceanread.com:460/";
  // this.typhoonQueryUrlFourCreat = "http://xxs.dhybzx.org:8008/typhoonHandler?";
  this.typhoonQueryUrlFourCreat = "https://xxs.dhybzx.org:3000/qstyphoon/typhoonHandler?";

  /**今日台风数组 */
  this.todayTyphoon = [];
  /**当前展示的台风ID数组 */
  this.typhoonIdArray = [];
  /**当前展示的台风对象数组 */
  this.typhoonObjArray = [];

  /**预报台名称集合(全局) */
  this.ybtNameArr = ["中国", "中国台湾", "中国香港", "美国", "日本", "韩国"];

  /**该预报台是否显示 */
  this.isYbtShow = {
    中国: true,
    中国台湾: true,
    中国香港: true,
    美国: true,
    日本: true,
    韩国: true,
  };

  /**表示popup是否打开 */
  this.isPopuping = false;

  /**当前打开的popup */
  this.thisPopup = null;

  /**台风路径数据缓存 */
  this.typhoonPathDataArray = {};

  // 屏幕宽高
  this.directWidth = $(window).width();
  this.directHeight = $(window).height();

  // 控件宽高
  this.btnBoxHeight = $(".right-btn-group").height(); // 按钮组高度
  this.btnBoxWidth = $(".right-btn-group").width(); // 按钮组宽度
  this.copyrightHeight = $(".copyright").outerHeight(); // 版权文字外框高度（含padding）

  this.typhoonCircles = []; /** 所有奉劝 */
};

let pulseMarker = null;

/**(外部调用)初始化台风对象 */
Typhoon.prototype.init = function (param) {
  let self = this;
  self.map = param.map;
  self.drawWarningLine();
  self.queryTodayTyphoonFourCreat();
  self.map.on("moveend", function (event) {
    let zoomLevel = self.map.getZoom();
    if (zoomLevel < 6) {
      //移除
      if (self.map.hasLayer(self.polyline24Marker)) {
        self.map.removeLayer(self.polyline24Marker);
        self.map.removeLayer(self.polyline48Marker);
      }
      for (let index = 0; index < self.typhoonIdArray.length; index++) {
        let TYPHOON_ID = self.typhoonIdArray[index];
        if (self.map.hasLayer(self.typhoonObjArray[TYPHOON_ID].newTimeMarker)) {
          self.map.removeLayer(self.typhoonObjArray[TYPHOON_ID].newTimeMarker);
        }
        if (
          self.map.hasLayer(self.typhoonObjArray[TYPHOON_ID].TFcircleTextGroup)
        ) {
          self.map.removeLayer(
            self.typhoonObjArray[TYPHOON_ID].TFcircleTextGroup
          );
        }
        if (self.typhoonObjArray[TYPHOON_ID].forecastInfo["中国"]) {
          if (
            self.map.hasLayer(
              self.typhoonObjArray[TYPHOON_ID].forecastInfo["中国"]
                .ybTimeMarkerLayerGroup
            )
          ) {
            self.map.removeLayer(
              self.typhoonObjArray[TYPHOON_ID].forecastInfo["中国"]
                .ybTimeMarkerLayerGroup
            );
          }
        }
      }
    } else {
      //添加
      if (!self.map.hasLayer(self.polyline24Marker) && true) {
        self.polyline24Marker.addTo(self.map);
        self.polyline48Marker.addTo(self.map);
      }
      for (let index = 0; index < self.typhoonIdArray.length; index++) {
        let TYPHOON_ID = self.typhoonIdArray[index];
        if (
          !self.map.hasLayer(self.typhoonObjArray[TYPHOON_ID].newTimeMarker)
        ) {
          self.typhoonObjArray[TYPHOON_ID].newTimeMarker.addTo(self.map);
        }
        if (
          !self.map.hasLayer(self.typhoonObjArray[TYPHOON_ID].TFcircleTextGroup)
        ) {
          self.typhoonObjArray[TYPHOON_ID].TFcircleTextGroup.addTo(self.map);
        }
        if (self.isYbtShow["中国"]) {
          if (self.typhoonObjArray[TYPHOON_ID].forecastInfo["中国"]) {
            if (
              !self.map.hasLayer(
                self.typhoonObjArray[TYPHOON_ID].forecastInfo["中国"]
                  .ybTimeMarkerLayerGroup
              )
            ) {
              self.typhoonObjArray[TYPHOON_ID].forecastInfo[
                "中国"
              ].ybTimeMarkerLayerGroup.addTo(self.map);
            }
          }
        }
      }
      // 缩小标注字体
      let ty = $(
        ".divIcon-typhoon-textLabel,.divIcon-typhoon-circle-textLabel"
      );
      for (let i = 0; i < ty.length; i++) {
        let translate =
          "translate3d(" +
          ty[i]._leaflet_pos.x +
          "px, " +
          ty[i]._leaflet_pos.y +
          "px, 0px)";
        $(ty[i]).css("transform", translate + " scale(0.92)");
      }
    }
  });
  self.map.on("zoomstart", function (event) {
    $(".typhoonPopupClose").click(); //关闭popup弹窗
    $(".typhoonGif").hide();
  });
  self.map.on("zoomend", function (event) {
    setTimeout(function () {
      $(".typhoonGif").show();
    }, 300);
    self.redrawHistoryPoint();
  });
  window.onresize = function () {
    self.directWidth = $(window).width();
    self.directHeight = $(window).height();
  };
};

/**(外部调用)移除全部台风路径(通用方法) */
Typhoon.prototype.removeAllPath = function () {
  let self = this;
  let arr = self.deepCopyObj(self.typhoonIdArray);
  arr.forEach(function (el) {
    self.removeOnePath(el);
  });
};

/**(外部调用)移除某台风路径(通用方法) */
Typhoon.prototype.removeOnePath = function (TYPHOON_ID) {
  let self = this;
  if (self.typhoonObjArray[TYPHOON_ID]) {
    let thTyphoon = self.typhoonObjArray[TYPHOON_ID];
    //清除所有预报路径
    self.typhoonObjArray[TYPHOON_ID].forecastLineLayerGroup.removeFrom(
      self.map
    );
    self.typhoonObjArray[TYPHOON_ID].forecastPointLayerGroup.removeFrom(
      self.map
    );
    if (
      self.typhoonObjArray[TYPHOON_ID].forecastInfo["中国"] &&
      self.typhoonObjArray[TYPHOON_ID].forecastInfo["中国"]
        .ybTimeMarkerLayerGroup
    ) {
      self.typhoonObjArray[TYPHOON_ID].forecastInfo[
        "中国"
      ].ybTimeMarkerLayerGroup.removeFrom(self.map);
    }
    //清除历史路径
    self.typhoonObjArray[TYPHOON_ID].historyPointGroup.removeFrom(self.map);
    self.typhoonObjArray[TYPHOON_ID].historyLineGroup.removeFrom(self.map);
    //清除台风风圈
    if (thTyphoon.TFcircleGroup)
      self.typhoonObjArray[TYPHOON_ID].TFcircleGroup.removeFrom(self.map);
    if (thTyphoon.TFcircleTextGroup)
      self.typhoonObjArray[TYPHOON_ID].TFcircleTextGroup.removeFrom(self.map);
    //清除台风动图
    if (self.map.hasLayer(self.typhoonObjArray[TYPHOON_ID].windGif)) {
      self.map.removeLayer(self.typhoonObjArray[TYPHOON_ID].windGif);
      if (self.typhoonObjArray[TYPHOON_ID].windGif)
        clearInterval(self.typhoonObjArray[TYPHOON_ID].windGif.gifInterval);
    }
    //清除台风名称
    if (self.map.hasLayer(self.typhoonObjArray[TYPHOON_ID].nameMarker)) {
      self.map.removeLayer(self.typhoonObjArray[TYPHOON_ID].nameMarker);
    }
    if (self.map.hasLayer(self.typhoonObjArray[TYPHOON_ID].newTimeMarker)) {
      self.map.removeLayer(self.typhoonObjArray[TYPHOON_ID].newTimeMarker);
    }
    //移除某台风即销毁对象
    delete self.typhoonObjArray[TYPHOON_ID];
    self.typhoonIdArray = self.typhoonIdArray.filter(function (params) {
      return params != TYPHOON_ID;
    });

    self.removeTyphoonPromptText(TYPHOON_ID);
  }
};

/**(外部调用)移除风圈(通用方法) */
Typhoon.prototype.removeAllCircles = function () {
  let self = this,
    arr = self.deepCopyObj(self.typhoonIdArray);
  arr.forEach(function (el) {
    if (self.typhoonObjArray[el]) {
      let thTyphoon = self.typhoonObjArray[el];
      if (thTyphoon.TFcircleGroup)
        self.typhoonObjArray[el].TFcircleGroup.removeFrom(self.map);
      if (thTyphoon.TFcircleTextGroup)
        self.typhoonObjArray[el].TFcircleTextGroup.removeFrom(self.map);
      if (self.map.hasLayer(self.typhoonObjArray[el].windGif)) {
        self.map.removeLayer(self.typhoonObjArray[el].windGif);
        if (self.typhoonObjArray[el].windGif)
          clearInterval(self.typhoonObjArray[el].windGif.gifInterval);
      }
      if (self.map.hasLayer(self.typhoonObjArray[el].windGif)) {
        self.map.removeLayer(self.typhoonObjArray[el].windGif);
        if (self.typhoonObjArray[el].windGif)
          clearInterval(self.typhoonObjArray[el].windGif.gifInterval);
      }
    }
  });
};

/**(外部调用)根据时刻绘制该时刻风圈(通用方法) */
Typhoon.prototype.drawAllCircles = function (tm) {
  let self = this,
    arr = self.deepCopyObj(self.typhoonIdArray);
  self.removeAllCircles();
  arr.map((id) => {
    let pathData = self.typhoonPathDataArray?.[id],
      TFData = pathData?.length > 1 ? pathData[1] : pathData[0];
    if (TFData.status == "ok" && TFData?.data?.length > 0) {
      let thTF = TFData.data[0],
        sDate = new Date(thTF.begin_time),
        eDate = new Date(thTF.end_time);
      if (tm >= sDate && tm <= eDate && thTF.points.length > 0) {
        let nowPoint = thTF.points.findIndex(
          (po, poi) =>
            poi < thTF.points.length - 1 &&
            tm >= new Date(po.time) &&
            tm < new Date(thTF.points[poi + 1].time)
        );
        if (nowPoint == 0 || nowPoint) {
          self.drawTFCircles(thTF.points, id, nowPoint);
          let thpoint = thTF.points[nowPoint],
            posi = L.latLng(parseFloat(thpoint.lat), parseFloat(thpoint.lng));
          self.drawTFGIF(id, thpoint, posi);
        }
      }
    }
  });
};

/**(外部调用)打开或关闭某预报台显示(通用方法) */
Typhoon.prototype.changeYbtShow = function (ybtName, isShow) {
  let self = this;
  for (let index = 0; index < self.typhoonIdArray.length; index++) {
    let TYPHOON_ID = self.typhoonIdArray[index];
    if (isShow) {
      if (self.typhoonObjArray[TYPHOON_ID].forecastInfo[ybtName]) {
        //self.typhoonObjArray[TYPHOON_ID].forecastInfo[ybtName].yblayerGroup.addTo(self.map);
        self.typhoonObjArray[TYPHOON_ID].forecastInfo[
          ybtName
        ].ybLinelayerGroup.addTo(
          self.typhoonObjArray[TYPHOON_ID].forecastLineLayerGroup
        );
        self.typhoonObjArray[TYPHOON_ID].forecastInfo[
          ybtName
        ].ybPointlayerGroup.addTo(
          self.typhoonObjArray[TYPHOON_ID].forecastPointLayerGroup
        );
        if (ybtName === "中国") {
          self.typhoonObjArray[TYPHOON_ID].forecastInfo[
            ybtName
          ].ybTimeMarkerLayerGroup.addTo(self.map);
        }
      }
    } else {
      if (self.typhoonObjArray[TYPHOON_ID].forecastInfo[ybtName]) {
        //self.typhoonObjArray[TYPHOON_ID].forecastInfo[ybtName].yblayerGroup.removeFrom(self.map);
        self.typhoonObjArray[TYPHOON_ID].forecastInfo[
          ybtName
        ].ybLinelayerGroup.removeFrom(
          self.typhoonObjArray[TYPHOON_ID].forecastLineLayerGroup
        );
        self.typhoonObjArray[TYPHOON_ID].forecastInfo[
          ybtName
        ].ybPointlayerGroup.removeFrom(
          self.typhoonObjArray[TYPHOON_ID].forecastPointLayerGroup
        );
        if (ybtName === "中国") {
          self.typhoonObjArray[TYPHOON_ID].forecastInfo[
            ybtName
          ].ybTimeMarkerLayerGroup.removeFrom(self.map);
        }
      }
    }
  }
};

/**(外部调用)绘制今日台风 */
Typhoon.prototype.drawTodayTyphoon = function () {
  let self = this;
  for (let index = 0; index < self.todayTyphoon.length; index++) {
    if (index != self.todayTyphoon.length - 1) {
      self.drawOnePathFourCreat(self.todayTyphoon[index], "notLastOne"); //该参数表示当前台风不会setview
    } else {
      self.drawOnePathFourCreat(self.todayTyphoon[index]); //绘制当前台风
    }
  }
};

/**(外部调用)绘制某台风 */
Typhoon.prototype.drawTyphoon = function (baseInfo) {
  let self = this;
  self.drawOnePathFourCreat(baseInfo);
};

/**查询台风通用方法(FourCreat)*/
Typhoon.prototype.queryTFFourCreat = function (queryName, args, callback) {
  let self = this;
  $.ajax({
    url: self.typhoonQueryUrlFourCreat + queryName + args,
    // type: "post",
    type: "get",
    dataType: "json",
    // data: args,
    timeout: 6000,
    success: function (result) {
      callback(result);
    },
    error: function (e) {
      console.log(e);
      console.log("台风查询出错，请查看控制台！");
    },
  });
};

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
}

/**查询今日台风(FourCreat) */
Typhoon.prototype.queryTodayTyphoonFourCreat = function () {
  let self = this,
    year = new Date().getFullYear();
  let promise = new Promise(function (resolve, reject) {
    self.queryTFFourCreat(
      // "GetTyphoonByYear",
      // "?year=" + year,
      "m=getTyphoonListByYear",
      "&year=" + year,
      function (obj) {

        // 重构接口数据结构
        if (obj.success) {
          obj.status = "ok";
          obj.data = [];
          for (let i = 0; i < obj.resultData.length; i++) {
            const ele = obj.resultData[i];
            let is_current = 0;
            const today = new Date();
            if (ele.endTime.split(" ")[0] == formatDate(today)) {
              is_current = 1
              obj.data.push({
                tfbh: ele.TFBH,
                name: ele.TFM,
                ename: ele.TFME,
                is_current: is_current,
                begin_time: ele.beginTime,
                end_time: ele.endTime,
                land: [],
                points: [],
              });

            }


          }

          //   obj.data.push({
          //     tfbh: "",
          //     name: "",
          //     ename: "",
          //     is_current: 0,
          //     begin_time: "",
          //     end_time: "",
          //     land: [],
          //     points: [],
          //   });

          //   obj.data[0].points = obj.resultData;

          //   obj.data[0].points.map((item) => {
          //     item.tfbh = item.TFBH;
          //     item.time = item.RQSJ;
          //     item.lng = item.JD;
          //     item.lat = item.WD;
          //     item.strong = item.STRONG;
          //     item.power = item.POWER;
          //     item.speed = item.ZXFS;
          //     item.move_speed = item.YDSD;
          //     item.move_dir = item.YDFX;
          //     item.pressure = item.ZXQY;
          //     item.radius7 = item.RADIUS7;
          //     item.radius10 = item.RADIUS10;
          //     item.radius12 = item.RADIUS12;
          //     item.remark = item.ID;
          //     item.forecast = item.forecastPathList;
          //   });
          // }

          if (obj.status == "ok") {
            resolve(obj.data);
          } else {
            reject(obj.msg);
          }
        }
      }
    );
  });
  promise.then(
    function (data) {
      // data = data.filter(function (params) {
      //     if (params.tfbh.length <= 7) {
      //         return params
      //     }
      // })
      let newData = [];
      for (let i = 0; i < data.length; i++) {
        if (data[i].is_current === 1) {
          newData.push(data[i]);
        }
      }
      if (newData.length === 0) {
        // console.log("无台风"); //不显示无台风的文本
        // let textDiv = document.createElement("div");
        // textDiv.id = "typhoonText" + "_noTf";
        // textDiv.className = "promptTextStyle";
        // textDiv.innerHTML = "当前无台风";
        // document.getElementById("typhoonText").appendChild(textDiv);
        return;
      }
      self.todayTyphoon = newData;
      //不直接绘制 今日台风
      for (let index = 0; index < newData.length; index++) {
        if (index != newData.length - 1) {
          self.drawOnePathFourCreat(newData[index], "notLastOne"); //该参数表示当前台风不会setview
        } else {
          self.drawOnePathFourCreat(newData[index]); //绘制当前台风
        }
      }
    },
    function (error) {
      console.log(error);
    }
  );
};

/**绘制某台风路径(FourCreat) */
Typhoon.prototype.drawOnePathFourCreat = function (baseInfo) {
  /**本方法的第二个参数 */
  let argument2 = arguments[1];
  // TODO: FourCreat
  let self = this;
  /**此台风编号 */
  let TYPHOON_ID = baseInfo.tfbh;
  if ($.inArray(TYPHOON_ID, self.typhoonIdArray) < 0) {
    //self.typhoonIdArray.push(TYPHOON_ID); //执行绘制函数时将ID推入展示数组
  } else {
    return;
  }
  self.typhoonObjArray[TYPHOON_ID] = {};
  self.typhoonObjArray[TYPHOON_ID].baseInfo = baseInfo;
  self.typhoonObjArray[TYPHOON_ID].historyPointGroupHide = L.layerGroup();
  self.typhoonObjArray[TYPHOON_ID].historyPointGroup = L.layerGroup();
  self.typhoonObjArray[TYPHOON_ID].historyLineGroup = L.layerGroup();
  self.typhoonObjArray[TYPHOON_ID].TFcircleGroup = L.layerGroup();
  self.typhoonObjArray[TYPHOON_ID].TFcircleTextGroup = L.layerGroup();
  self.typhoonObjArray[TYPHOON_ID].forecastInfo = {};
  self.typhoonObjArray[TYPHOON_ID].forecastPointLayerGroup = L.layerGroup();
  self.typhoonObjArray[TYPHOON_ID].forecastLineLayerGroup = L.layerGroup();
  /**当前台风名称 */
  let curName = baseInfo.name + "(" + baseInfo.ename + ")";
  /**当前预报台名称集合 */
  let ybtNameArr = [];
  /**异步数组 */
  let promiseArray = [];
  if (self.typhoonPathDataArray[TYPHOON_ID]) {
    self.drawMethod(
      self.typhoonPathDataArray[TYPHOON_ID],
      TYPHOON_ID,
      curName,
      ybtNameArr,
      baseInfo,
      argument2
    );
  } else {
    if (baseInfo.is_current) {
      if (baseInfo.is_current === 1) {
        promiseArray.push(
          new Promise((resolve, reject) => {
            //查询台风的最新信息
            self.queryTFFourCreat(
              // 'GetTyphoonDescByID',
              // '?id=' + TYPHOON_ID,
              "m=getTyphoonPathListByID",
              "&tyID=" + TYPHOON_ID,
              function (obj) {
                if (obj) {
                  resolve(obj);
                } else {
                  reject("err");
                }
              }
            );
          })
        );
      }
    }
    promiseArray.push(
      new Promise((resolve, reject) => {
        //查询台风的路径信息
        self.queryTFFourCreat(
          // 'GetTyphoonRouteByID',
          // '?id=' + TYPHOON_ID,
          "m=getTyphoonPathListByID",
          "&tyID=" + TYPHOON_ID,
          function (obj) {
            if (obj) {
              // 重构接口数据结构
              if (obj.success) {
                obj.status = "ok";

                obj.data = [];
                obj.data.push({
                  tfbh: "",
                  name: "",
                  ename: "",
                  is_current: 0,
                  begin_time: "",
                  end_time: "",
                  land: [],
                  points: [],
                });

                obj.data[0].points = obj.resultData;

                obj.data[0].points.map((item) => {
                  item.tfbh = item.TFBH;
                  item.time = item.RQSJ;
                  item.lng = item.JD;
                  item.lat = item.WD;
                  item.strong = item.STRONG;
                  item.power = item.POWER;
                  item.speed = item.ZXFS;
                  item.move_speed = item.YDSD;
                  item.move_dir = item.YDFX;
                  item.pressure = item.ZXQY;
                  item.radius7 = item.RADIUS7;
                  item.radius10 = item.RADIUS10;
                  item.radius12 = item.RADIUS12;
                  item.remark = item.ID;
                  item.forecast = null; // item.forecastPathList;
                });
              }
              // console.log(obj);
              // chun.tfInfo = obj;
              resolve(obj);
            } else {
              reject("err");
            }
          }
        );
      })
    );
    Promise.all(promiseArray)
      .then(
        (result) => {
          if (!self.typhoonPathDataArray[TYPHOON_ID]) {
            self.typhoonPathDataArray[TYPHOON_ID] = result;
          }
          self.drawMethod(
            result,
            TYPHOON_ID,
            curName,
            ybtNameArr,
            baseInfo,
            argument2
          );
        },
        (error) => {
          console.log(error);
        }
      )
      .catch((error) => {
        console.log(error);
      });
  }
};

/**绘制(子方法)*/
Typhoon.prototype.drawMethod = function (
  result,
  TYPHOON_ID,
  curName,
  ybtNameArr,
  baseInfo,
  argument2
) {
  let self = this,
    obj,
    newInfo,
    newPointContent = {};
  if (result.length == 1) {
    obj = result[0];
  } else if (result.length == 2) {
    newInfo = result[0];
    obj = result[1];
  }
  if (obj.status != "ok") {
    console.log(obj.msg);
    return;
  }
  if (obj.data.length <= 0 || obj.data.constructor != Array) {
    alert("数据异常！");
    return;
  }
  self.typhoonIdArray.push(TYPHOON_ID); //将ID推入展示数组
  let data = obj.data[0].points;
  /**本次路径全部信息 */
  let tfdata_all = [];
  /**存储线坐标数组 用于turf求bbox */
  let lineArr = [];
  for (let i = 0; i < data.length; i++) {
    tfdata_all.push(data[i]);
  }
  self.typhoonObjArray[TYPHOON_ID].tfdata_all = tfdata_all; //记录下数据用于查询
  //绘制台风名称
  let posi = L.latLng(
    parseFloat(tfdata_all[0].lat),
    parseFloat(tfdata_all[0].lng)
  );
  let nameMarker = L.marker(posi, {
    icon: L.divIcon({
      iconSize: [0, 0],
      iconAnchor: [0, 0],
      className: "divIcon-typhoon-name",
      html: '<div style="margin:5px 0 0 5px;color:red;">' + curName + "</div>",
    }),
    // pane: "overlayPane",
    zIndexOffset: -1000,
  }).addTo(self.map);
  self.typhoonObjArray[TYPHOON_ID].nameMarker = nameMarker;
  //然后绘制路径折点、线段

  // 存储预报机构
  let ybtName = [];
  let lastTime = tfdata_all[tfdata_all.length - 1].RQSJ;
  let isCurrent = lastTime === formatDate(new Date());

  // for (let i = 0; i < tfdata_all.length; i++) {
  for (let i = tfdata_all.length - 1; i >= 0; i--) {
    let mydata = tfdata_all[i];
    // console.log(mydata);
    /**折点位置 */
    let posi = L.latLng(parseFloat(mydata.lat), parseFloat(mydata.lng));
    lineArr.push([posi.lng, posi.lat]);
    let mycolor = self.setHistoryColor(mydata.power);
    if (typeof mycolor == "undefined") {
      //为台风折点,设置默认颜色
      mycolor = "rgba(255,69,0,1)";
    }
    /**路径折点 */
    let cir = L.circleMarker(posi, {
      weight: 0.5,
      color: "rgb(0,0,0)",
      radius: 4,
      fillColor: mycolor,
      fill: true,
      stroke: true,
      fillOpacity: 1,
      pane: "markerPane" /* i < tfdata_all.length - 1 ? "markerPane" : "shadowPane" */,
      // pane: "shadowPane"
    });
    //折点弹窗事件
    let latString, lngString;
    if (parseFloat(mydata.lng) > 0) {
      lngString = "东经";
    } else {
      lngString = "西经";
    }
    if (parseFloat(mydata.lat) > 0) {
      latString = "北纬";
    } else {
      latString = "南纬";
    }
    // let timeString1 = mydata.time.split("T")[0];
    // let timeString2 = mydata.time.split("T")[1];
    let timeString1 = mydata.time.split(" ")[0];
    let timeString2 = mydata.time.split(" ")[1];
    let timeString =
      parseInt(timeString1.split("-")[1]) +
      "月" +
      parseInt(timeString1.split("-")[2]) +
      "日" +
      parseInt(timeString2.split(":")[0]) +
      "时";
    let titleString = curName + "\xa0\xa0\xa0\xa0" + timeString;
    let contentArray = [];
    contentArray.push({
      label: "中心位置",
      id: "center",
      value:
        lngString + mydata.lng + "°\xa0\xa0" + latString + mydata.lat + "°",
    });
    let strong = mydata.strong;
    let strongStr = strong ? "(" + strong.split("(")[0] + ")" : "";
    if (mydata.speed && mydata.power) {
      contentArray.push({
        label: "风速风力",
        id: "power",
        value: mydata.speed + "米/秒\xa0\xa0" + mydata.power + "级" + strongStr,
      });
    }
    if (mydata.pressure) {
      contentArray.push({
        label: "中心气压",
        id: "press",
        value: mydata.pressure + "百帕",
      });
    }
    if (i === tfdata_all.length - 1) {
      //最新信息绑定
      if (newInfo && newInfo.status == "ok") {
        if (newInfo.data.location) {
          contentArray.push({
            label: "位置信息",
            id: "position",
            value: newInfo.data.location,
          });
        }
        if (newInfo.data.completion) {
          contentArray.push({
            label: "移动趋势",
            id: "trend",
            value: newInfo.data.completion,
          });
        }
      }
    }
    let typhoonPopupCont = self.creatTyphoonPopupCont({
      title: titleString,
      cont: contentArray,
    });
    if (i === tfdata_all.length - 1) {
      //最新信息绑定
      newPointContent.typhoonPopupCont = typhoonPopupCont;
      newPointContent.contentArray = contentArray;
      newPointContent.titleString = titleString;
      /**最新历史时刻的时间标注 */
      let newTimeMarker = L.marker(posi, {
        icon: L.divIcon({
          iconSize: [0, 0],
          iconAnchor: [0, 0],
          className: "divIcon-typhoon-textLabel",
          html: '<div style="margin: -8px 0 0 18px;">' + timeString + "</div>",
        }),
        zIndexOffset: 1,
      }).addTo(self.map);
      self.typhoonObjArray[TYPHOON_ID].newTimeMarker = newTimeMarker;
    }
    if (i < tfdata_all.length - 1) {
      cir.bindPopup(typhoonPopupCont, {
        offset: L.point(0, 0),
        className: "typhoonPopup",
        closeButton: false,
        closeOnClick: true,
        autoPan: false,
      });
      cir.on("popupopen", function (popupEvent) {
        self.changeMapPosition(cir, popupEvent);
        if (!self.isPopuping) {
          self.dataQueryInOpenPopup(cir, mydata, contentArray, titleString);
        }
        self.isPopuping = true;
        self.thisPopup = cir.getPopup();
        $(".leaflet-popup-pane").off();
        $(".leaflet-popup-pane").on("click", ".typhoonPopupClose", function () {
          if (cir !== null) cir.closePopup();
        });
      });
      cir.on("popupclose", function () {
        chun.tfInfo.name = "";
        if (pulseMarker) {
          pulseMarker.remove();
        }
        self.isPopuping = false;
        self.thisPopup = null;
      });
    }

    self.typhoonObjArray[TYPHOON_ID].historyPointGroupHide.addLayer(cir);
    self.typhoonObjArray[TYPHOON_ID].historyPointGroup.addLayer(cir);
    //为历史路径添加折线
    if (i !== tfdata_all.length - 1) {
      let posi_1 = L.latLng(
        parseFloat(tfdata_all[i + 1].lat),
        parseFloat(tfdata_all[i + 1].lng)
      );
      let latlngs = [posi, posi_1];
      let line = L.polyline(latlngs, {
        color: mycolor,
        weight: 2,
        pane: "shadowPane"
      });
      self.typhoonObjArray[TYPHOON_ID].historyLineGroup.addLayer(line);
    }

    mydata.forecast = mydata.forecastPathList;
    //每个点均可能有预报路径
    // if (!mydata.forecast||formatDate(new Date(mydata.time))!=formatDate(new Date())) {
    //   continue;
    // }
    if (!mydata.forecast || !isCurrent) {
      continue;
    }
    if (mydata.forecast.length === 0) {
      continue;
    }
    // if (mydata.forecast.length > 0&&i==result[0].resultData.length-1) {
    if (mydata.forecast.length > 0) {
      for (let i = 0; i < mydata.forecast.length; i++) {
        let thisData = mydata.forecast[i];
        thisData.points = thisData.pathList.map((item) => {
          item.tfbh = item.TFBH;
          item.time = item.RQSJ;
          item.lng = item.JD;
          item.lat = item.WD;
          item.strong = item.STRONG;
          item.power = item.POWER;
          item.speed = item.ZXFS;
          item.move_speed = item.YDSD;
          item.move_dir = item.YDFX;
          item.pressure = item.ZXQY;
          item.radius7 = item.RADIUS7;
          item.radius10 = item.RADIUS10;
          item.radius12 = item.RADIUS12;
          item.remark = item.ID;
          return item;
        })
        /**本预报台名称 */
        let thisYbtName = thisData.organizationName;
        if (!ybtName.includes(thisYbtName)&&!thisYbtName.includes("？")) {
          ybtName.push(thisYbtName);
        }else{
          continue;
        }
        
        
        if ($.inArray(thisYbtName, self.ybtNameArr) < 0) {
          continue;
        }
        /**本预报台颜色 */
        let lineColor = self.setYbtColor(thisYbtName);
        if ($.inArray(thisYbtName, ybtNameArr) < 0) {
          ybtNameArr.push(thisYbtName);
        }
        self.typhoonObjArray[TYPHOON_ID].forecastInfo[thisYbtName] = {};
        self.typhoonObjArray[TYPHOON_ID].forecastInfo[thisYbtName].ybInfo =
          thisData.points;
        //self.typhoonObjArray[TYPHOON_ID].forecastInfo[thisYbtName].yblayerGroup = L.layerGroup();
        self.typhoonObjArray[TYPHOON_ID].forecastInfo[
          thisYbtName
        ].ybPointlayerGroup = L.layerGroup();
        self.typhoonObjArray[TYPHOON_ID].forecastInfo[
          thisYbtName
        ].ybLinelayerGroup = L.layerGroup();
        if (thisYbtName === "中国") {
          self.typhoonObjArray[TYPHOON_ID].forecastInfo[
            thisYbtName
          ].ybTimeMarkerLayerGroup = L.layerGroup();
          if (self.isYbtShow[thisYbtName]) {
            self.typhoonObjArray[TYPHOON_ID].forecastInfo[
              thisYbtName
            ].ybTimeMarkerLayerGroup.addTo(self.map);
          }
        }
        if (self.isYbtShow[thisYbtName]) {
          //判断该预报台是否显示
          //self.typhoonObjArray[TYPHOON_ID].forecastInfo[thisYbtName].yblayerGroup.addTo(self.map);
          self.typhoonObjArray[TYPHOON_ID].forecastInfo[
            thisYbtName
          ].ybPointlayerGroup.addTo(
            self.typhoonObjArray[TYPHOON_ID].forecastPointLayerGroup
          );
          self.typhoonObjArray[TYPHOON_ID].forecastInfo[
            thisYbtName
          ].ybLinelayerGroup.addTo(
            self.typhoonObjArray[TYPHOON_ID].forecastLineLayerGroup
          );
        }
        if (thisData.points.length > 0) {
          //取历史路径的当前点
          let point_0 = L.latLng(
            parseFloat(mydata.lat),
            parseFloat(mydata.lng)
          );
          //首先添加首段线
          self.typhoonObjArray[TYPHOON_ID].forecastInfo[
            thisYbtName
          ].ybLinelayerGroup.addLayer(
            L.polyline(
              [
                point_0,
                L.latLng(
                  parseFloat(thisData.points[0].lat),
                  parseFloat(thisData.points[0].lng)
                ),
              ],
              {
                color: lineColor,
                weight: 2,
                dashArray: "5",
                pane: "shadowPane"
              }
            )
          );
          for (let j = 0; j < thisData.points.length; j++) {
            let posi = L.latLng(
              parseFloat(thisData.points[j].lat),
              parseFloat(thisData.points[j].lng)
            );
            let mycolor = self.setHistoryColor(thisData.points[j].power);
            if (j !== thisData.points.length - 1) {
              //添加预报路径折线
              let posi_1 = L.latLng(
                parseFloat(thisData.points[j + 1].lat),
                parseFloat(thisData.points[j + 1].lng)
              );
              let latlngs = [posi, posi_1];
              let line = L.polyline(latlngs, {
                color: lineColor,
                weight: 2,
                dashArray: "5",
                pane: "shadowPane"
              });
              self.typhoonObjArray[TYPHOON_ID].forecastInfo[
                thisYbtName
              ].ybLinelayerGroup.addLayer(line);
            }
            let cir = L.circleMarker(posi, {
              //预报路径折点
              weight: 0.5,
              color: "rgb(0,0,0)",
              radius: 4,
              fillColor: mycolor,
              fill: true,
              stroke: true,
              fillOpacity: 1,
              pointid: j,
              pane: "markerPane",
              // pane: "shadowPane"
            });
            //折点弹窗事件
            let latString, lngString;
            if (parseFloat(thisData.points[j].lng) > 0) {
              lngString = "东经";
            } else {
              lngString = "西经";
            }
            if (parseFloat(thisData.points[j].lat) > 0) {
              latString = "北纬";
            } else {
              latString = "南纬";
            }
            let timeString1 = thisData.points[j].time.split(" ")[0];
            let timeString2 = thisData.points[j].time.split(" ")[1];
            let timeString =
              parseInt(timeString1.split("-")[1]) +
              "月" +
              parseInt(timeString1.split("-")[2]) +
              "日" +
              parseInt(timeString2?.split(":")[0]) +
              "时";
            let timeString3 =
              parseInt(timeString1?.split("-")[2]) +
              "日" +
              parseInt(timeString2?.split(":")[0]) +
              "时";
            // let titleString = thisYbtName + "\xa0\xa0\xa0\xa0" + timeString;
            let titleString = `${baseInfo.name}(${baseInfo.ename}`;
            let contentArray = [];
            contentArray.push({
              label: "中心位置",
              id: "center",
              value:
                lngString +
                thisData.points[j].lng +
                "°\xa0\xa0" +
                latString +
                thisData.points[j].lat +
                "°",
            });
            let strong = thisData.points[j].strong;
            let strongStr = strong ? "(" + strong.split("(")[0] + ")" : "";
            if (thisData.points[j].speed && thisData.points[j].power) {
              contentArray.push({
                label: "风速风力",
                id: "power",
                value:
                  thisData.points[j].speed +
                  "米/秒\xa0\xa0" +
                  thisData.points[j].power +
                  "级" +
                  strongStr,
              });
            }
            if (thisData.points[j].pressure) {
              contentArray.push({
                label: "中心气压",
                id: "press",
                value: thisData.points[j].pressure + "百帕",
              });
            }
            let typhoonPopupCont = self.creatTyphoonPopupCont({
              title: titleString,
              cont: contentArray,
            });
            cir.bindPopup(typhoonPopupCont, {
              offset: L.point(0, 0),
              className: "typhoonPopup",
              closeButton: false,
              closeOnClick: true,
              autoPan: false,
            });
            cir.on("popupopen", function (popupEvent) {
              self.changeMapPosition(cir, popupEvent);
              if (!self.isPopuping) {
                self.dataQueryInOpenPopup(
                  cir,
                  thisData.points[j],
                  contentArray,
                  titleString
                );
              }
              self.isPopuping = true;
              self.thisPopup = cir.getPopup();
              $(".leaflet-popup-pane").off();
              $(".leaflet-popup-pane").on(
                "click",
                ".typhoonPopupClose",
                function () {
                  if (cir !== null) cir.closePopup();
                }
              );
            });
            cir.on("popupclose", function () {
              // console.log(666);
              chun.tfInfo.name = "";
              if (pulseMarker) {
                pulseMarker.remove();
              }
              self.isPopuping = false;
              self.thisPopup = null;
            });
            self.typhoonObjArray[TYPHOON_ID].forecastInfo[
              thisYbtName
            ].ybPointlayerGroup.addLayer(cir);
            if (thisYbtName === "中国") {
              /**预报路径的时间标注 */
              let ybNewTimeMarker = L.marker(posi, {
                icon: L.divIcon({
                  iconSize: [0, 0],
                  iconAnchor: [0, 0],
                  className: "divIcon-typhoon-textLabel",
                  html:
                    '<div style="margin: -8px 0 0 12px;">' +
                    timeString3 +
                    "</div>",
                }),
                zIndexOffset: 1,
              });
              self.typhoonObjArray[TYPHOON_ID].forecastInfo[
                thisYbtName
              ].ybTimeMarkerLayerGroup.addLayer(ybNewTimeMarker);
            }
          }
        }
      }
    }
  }

  console.log(ybtName);
  

  // //求取本条路径的中心点
  // let bbox;
  // if (lineArr.length <= 1) {
  //     bbox = [lineArr[0][0] - 1, lineArr[0][1] - 1, lineArr[0][0] + 1, lineArr[0][1] + 1];
  // } else {
  //     let line_out = turf.lineString(lineArr);
  //     bbox = turf.bbox(line_out); //extent in minX, minY, maxX, maxY order
  // }
  // //self.map.fitBounds([[bbox[1] - 1, bbox[0] - 1], [bbox[3] + 1, bbox[2] + 1]]);
  // self.typhoonObjArray[TYPHOON_ID].bbox = bbox;

  //然后绘制风圈
  self.drawTFCircles(tfdata_all, TYPHOON_ID);

  let dataFinal = tfdata_all[tfdata_all.length - 1],
    posiFinal = L.latLng(parseFloat(dataFinal.lat), parseFloat(dataFinal.lng));

  self.drawTFGIF(TYPHOON_ID, dataFinal, posiFinal, newPointContent, true);

  self.typhoonObjArray[TYPHOON_ID].historyLineGroup.addTo(self.map);
  self.typhoonObjArray[TYPHOON_ID].forecastLineLayerGroup.addTo(self.map);
  self.typhoonObjArray[TYPHOON_ID].historyPointGroup.addTo(self.map);
  self.typhoonObjArray[TYPHOON_ID].forecastPointLayerGroup.addTo(self.map);
  self.typhoonObjArray[TYPHOON_ID].TFcircleGroup.addTo(self.map);
  self.typhoonObjArray[TYPHOON_ID].TFcircleTextGroup.addTo(self.map);
  self.addTyphoonPromptText(
    TYPHOON_ID,
    baseInfo.name,
    dataFinal.power,
    posiFinal
  );
  if (!argument2) {
    let centerp = self.map.latLngToContainerPoint(posiFinal);
    let offsetlatlng = self.map.containerPointToLatLng([
      centerp.x + 25,
      centerp.y + 100,
    ]);
    self.map.setView(offsetlatlng, 5);
    self.redrawHistoryPoint();
  }
};

/**绘制风圈(通用方法) */
Typhoon.prototype.drawTFGIF = function (
  TYPHOON_ID,
  dataFinal,
  posiFinal,
  newPointContent
) {
  let self = this;
  // if (self.map.hasLayer(self.typhoonObjArray[TYPHOON_ID].windGif)) {
  //     self.map.removeLayer(self.typhoonObjArray[TYPHOON_ID].windGif);
  //     if (self.typhoonObjArray[TYPHOON_ID].windGif) clearInterval(self.typhoonObjArray[TYPHOON_ID].windGif.gifInterval);
  // }
  //然后绘制台风动图
  let windGif = L.marker(posiFinal, {
    icon: L.divIcon({
      className:
        "typhoonGif typhoonGif-" +
        TYPHOON_ID +
        " typhoonGif-" +
        self.setHistoryPower(dataFinal.power),
      iconSize: [124, 124],
      iconAnchor: [62, 62],
    }),
    bubblingMouseEvents: false,
    interactive: true,
    pane: "markerPane",
  });
  // TODO FourCreat GIF
  windGif.addTo(self.map);
  let ty = $(".typhoonGif-" + TYPHOON_ID),
    rotate = 0;
  let translate =
    "translate3d(" +
    ty[0]._leaflet_pos.x +
    "px, " +
    ty[0]._leaflet_pos.y +
    "px, 0px)";
  ty.css("transform", translate + " rotate(-" + rotate + "deg) scale(0.2)");
  ty.removeClass("leaflet-zoom-animated");
  windGif.gifInterval = setInterval(function () {
    translate =
      "translate3d(" +
      ty[0]._leaflet_pos.x +
      "px, " +
      ty[0]._leaflet_pos.y +
      "px, 0px)";
    rotate = rotate >= 360 ? 0 : rotate + 10;
    ty.css("transform", translate + " rotate(-" + rotate + "deg) scale(0.2)");
  }, 60);
  setTimeout(() => {
    ty.show();
  }, 300);
  if (newPointContent) {
    windGif.bindPopup(newPointContent.typhoonPopupCont, {
      offset: L.point(0, 0),
      className: "typhoonPopup",
      closeButton: false,
      closeOnClick: true,
      autoPan: false,
    });
    windGif.on("popupopen", function (popupEvent) {
      self.changeMapPosition(windGif, popupEvent);
      if (!self.isPopuping) {
        self.dataQueryInOpenPopup(
          windGif,
          dataFinal,
          newPointContent.contentArray,
          newPointContent.titleString
        );
      }
      self.isPopuping = false;
      self.thisPopup = windGif.getPopup();
      $(".leaflet-popup-pane").off();
      $(".leaflet-popup-pane").on("click", ".typhoonPopupClose", function () {
        if (windGif !== null) windGif.closePopup();
      });
    });
    windGif.on("popupclose", function () {
      // console.log(6666);
      chun.tfInfo.name = "";
      if (pulseMarker) {
        pulseMarker.remove();
      }
      self.isPopuping = false;
      self.thisPopup = null;
    });
    windGif.on("mouseover", function (params) {
      windGif.openPopup();
    });
    windGif.on("mouseout", function (params) {
      windGif.closePopup();
    });
    windGif.on("click", function (params) {
      windGif.openPopup();
    });
    windGif.isPopupShown = true; // 是否为第一次显示popup
    setTimeout(function () {
      windGif.openPopup();
    }, 500);
  }
  self.typhoonObjArray[TYPHOON_ID].windGif = windGif;
};

/**绘制风圈(通用方法) */
Typhoon.prototype.drawTFCircles = function (TFdata, TYPHOON_ID, index) {
  let self = this;
  let thTyphoon = self.typhoonObjArray?.[TYPHOON_ID];
  // if (thTyphoon.TFcircleGroup) thTyphoon.TFcircleGroup.removeFrom(self.map);
  // if (thTyphoon.TFcircleTextGroup) thTyphoon.TFcircleTextGroup.removeFrom(self.map);
  thTyphoon.TFcircleGroup = L.layerGroup().addTo(self.map);
  thTyphoon.TFcircleTextGroup = L.layerGroup().addTo(self.map);
  //绘制四个级别 7级 8级 10级 12级 台风圆圈
  let tfcircle7 = L.tfcirclelayer({
    opacity: 0.5,
    strokeStyle: "rgba(0,139,139,0.6)",
    fillStyle: "rgba(0,205,205,0.2)",
    showLabel: false,
  });
  let tfcircle10 = L.tfcirclelayer({
    opacity: 0.5,
    strokeStyle: "rgba(255,193,37,0.8)",
    fillStyle: "rgba(255,193,37,0.2)",
    showLabel: false,
  });
  let tfcircle12 = L.tfcirclelayer({
    opacity: 0.5,
    strokeStyle: "rgba(255,69,0,0.6)",
    fillStyle: "rgba(255,69,0,0.2)",
    showLabel: false,
  });
  self.typhoonObjArray[TYPHOON_ID].TFcircleGroup.addLayer(tfcircle7);
  self.typhoonObjArray[TYPHOON_ID].TFcircleGroup.addLayer(tfcircle10);
  self.typhoonObjArray[TYPHOON_ID].TFcircleGroup.addLayer(tfcircle12);
  let dataFinal = TFdata[index ?? TFdata.length - 1];
  if (dataFinal.radius7_quad) {
    self.TFcircleSetData(
      tfcircle7,
      dataFinal.lng,
      dataFinal.lat,
      dataFinal.radius7_quad.se,
      dataFinal.radius7_quad.sw,
      dataFinal.radius7_quad.nw,
      dataFinal.radius7_quad.ne
    );
    let marker7 = self.calLngIncrement(
      dataFinal,
      dataFinal.radius7_quad.se,
      dataFinal.radius7_quad.sw,
      dataFinal.radius7_quad.nw,
      dataFinal.radius7_quad.ne,
      "7级风圈"
    );
    if (marker7) {
      self.typhoonObjArray[TYPHOON_ID].TFcircleTextGroup.addLayer(marker7);
    }
  }
  if (dataFinal.radius10_quad) {
    self.TFcircleSetData(
      tfcircle10,
      dataFinal.lng,
      dataFinal.lat,
      dataFinal.radius10_quad.se,
      dataFinal.radius10_quad.sw,
      dataFinal.radius10_quad.nw,
      dataFinal.radius10_quad.ne
    );
    let marker10 = self.calLngIncrement(
      dataFinal,
      dataFinal.radius10_quad.se,
      dataFinal.radius10_quad.sw,
      dataFinal.radius10_quad.nw,
      dataFinal.radius10_quad.ne,
      "10级风圈"
    );
    if (marker10) {
      self.typhoonObjArray[TYPHOON_ID].TFcircleTextGroup.addLayer(marker10);
    }
  }
  if (dataFinal.radius12_quad) {
    self.TFcircleSetData(
      tfcircle12,
      dataFinal.lng,
      dataFinal.lat,
      dataFinal.radius12_quad.se,
      dataFinal.radius12_quad.sw,
      dataFinal.radius12_quad.nw,
      dataFinal.radius12_quad.ne
    );
    let marker12 = self.calLngIncrement(
      dataFinal,
      dataFinal.radius12_quad.se,
      dataFinal.radius12_quad.sw,
      dataFinal.radius12_quad.nw,
      dataFinal.radius12_quad.ne,
      "12级风圈"
    );
    if (marker12) {
      self.typhoonObjArray[TYPHOON_ID].TFcircleTextGroup.addLayer(marker12);
    }
  }
};

/**openPopup时调整地图中心(通用方法)  */
Typhoon.prototype.changeMapPosition = function (mark, popupEvent) {
  return;
  let self = this;
  let clientHeight = popupEvent.popup._container.clientHeight,
    clientWidth = popupEvent.popup._container.clientWidth,
    clientWidthHalf = Math.round(clientWidth / 2),
    btnBoxHeight = self.btnBoxHeight + 20, // 按钮组高度（上下空出10像素）
    btnBoxWidth = self.btnBoxWidth + 20, // 按钮组宽度（上下空出10像素）
    copyrightHeight = self.copyrightHeight + 15; // 版权文字高度（上方空出10像素）
  popupEvent.popup._container.style.bottom = "-" + (clientHeight + 16) + "px";
  let latlng = mark.getLatLng();
  let latlngp = self.map.latLngToContainerPoint(latlng);
  latlngp.y += 16;
  /**距离屏幕底端y值 */
  let yDisBottom = self.directHeight - latlngp.y;
  /**距离屏幕右端x值 */
  let xDisRight = self.directWidth - latlngp.x;

  let mapCenter = self.map.getCenter();
  let centerp = self.map.latLngToContainerPoint(mapCenter);
  let xx = Math.round(centerp.x),
    yy = Math.round(centerp.y),
    prexx = xx,
    preyy = yy;

  //因为调整了popup的上下位置,所以距离屏幕底端宽度不足时,应调整距离
  //调整下距离
  if (yDisBottom - clientHeight < copyrightHeight) {
    let offsety = copyrightHeight - (yDisBottom - clientHeight);
    latlngp.y -= offsety;
    yy = yy + offsety;
  }

  //调整左右距离（距离左右边框至少10像素）
  if (latlngp.x - clientWidthHalf < 10) {
    // 距离屏幕左边小于10像素
    xx = xx - (clientWidthHalf - latlngp.x + 10);
  } else if (xDisRight - clientWidthHalf < 10) {
    // 距离屏幕右边小于10像素
    if (latlngp.y > btnBoxHeight) {
      // 位于按钮组下方，未被按钮组遮挡
      xx = xx + (clientWidthHalf - xDisRight + 10);
    } else {
      // 被按钮组遮挡
      xx = xx + (btnBoxWidth - (xDisRight - clientWidthHalf));
    }
  } else if (xDisRight - clientWidthHalf <= btnBoxWidth) {
    // 距离屏幕右边小于按钮组宽度
    if (latlngp.y <= btnBoxHeight) {
      // 特殊调整右距离，防止按钮组压盖popup关闭按钮
      xx = xx + (btnBoxWidth - (xDisRight - clientWidthHalf));
    }
  }

  if (xx !== prexx || yy !== preyy) {
    console.log(xx, yy);
    let offsetlatlng = self.map.containerPointToLatLng([xx, yy]);
    if (!mark.isPopupShown) self.map.setView(offsetlatlng, self.map.getZoom());
  }
  mark.isPopupShown = false;
};

const checkIsOk = (value) => {
  if (value === null || value === undefined || value === '' || value == 'null') return false;
  return true;
}

/**数据查询(在OpenPopup时)(通用方法)  */
Typhoon.prototype.dataQueryInOpenPopup = function (
  cir,
  mydata,
  contentArray,
  titleString
) {
  const { _latlng, options } = cir
  // 清空之前的脉冲图标
  if (pulseMarker) {
    this.map.removeLayer(pulseMarker);
  }
  if (options.fillColor) {
    var pulsingIcon = L.icon.pulse({ iconSize: [7, 7], color: options.fillColor, fillColor: options.fillColor });
    pulseMarker = L.marker([_latlng.lat, _latlng.lng], { icon: pulsingIcon }).addTo(this.map);
  }
  // console.log(cir,contentArray,titleString);
  let self = this;
  chun.tfInfo.position = `东经${mydata.JD}° 北纬${mydata.WD}°`;
  chun.tfInfo.time = mydata.RQSJ;
  
  let basePosition = [30.438361, 120.954109];
  let distance = Math.sqrt(
    Math.pow(mydata.JD - basePosition[1], 2) +
    Math.pow(mydata.WD - basePosition[0], 2)
  );
  chun.tfInfo.distance = `${(distance * 100).toFixed(2)}km`;
  chun.tfInfo.name = mydata.TM ? mydata.TM : titleString.split(")")[0] + ")";
  chun.tfInfo.speed = checkIsOk(mydata.speed) ? mydata.speed + "m/s" : '';
  chun.tfInfo.power = mydata.power + "级" + "(" + mydata.strong + ")";
  chun.tfInfo.pressure = checkIsOk(mydata.pressure) ? mydata.pressure + "百帕" : '';
  chun.tfInfo.moveSpeed = checkIsOk(mydata.move_speed) ? mydata.move_speed + "km/h" : '';
  chun.tfInfo.moveDir = checkIsOk(mydata.move_dir) ? mydata.move_dir : '';
  chun.tfInfo.radius = `${checkIsOk(mydata.radius7) ? mydata.radius7 : '-'}/${checkIsOk(mydata.radius10) ? mydata.radius10 : '-'}/${checkIsOk(mydata.radius12) ? mydata.radius12 : '-'}`;
  // for(let key of Object.keys(mydata)){
  //   chun.tfInfo[key]=mydata[key]
  // }
  // console.log(chun.tfInfo);
  return;
};

/**绘制警戒线(通用方法) */
Typhoon.prototype.drawWarningLine = function () {
  let self = this;
  let warn_line24 = {
    points: [
      [0, 105],
      [4.5, 113],
      [11, 119],
      [18, 119],
      [22, 127],
      [34, 127],
    ],
    label: {
      title: "24小时警戒线",
      latlng: [28, 127],
      color: "red",
      iconSize: [21, 18],
      iconAnchor: [6, 20],
      minZoom: 5,
    },
  };
  let warn_line48 = {
    points: [
      [0, 105],
      [0, 120],
      [15, 132],
      [34, 132],
    ],
    label: {
      title: "48小时警戒线",
      latlng: [28, 132],
      color: "green",
      iconSize: [21, 18],
      iconAnchor: [6, 20],
      minZoom: 5,
    },
  };
  self.polyline24 = L.polyline(warn_line24.points, {
    color: "red",
    weight: 1,
    opacity: 0.9,
    // pane: "shadowPane"
  });
  self.polyline48 = L.polyline(warn_line48.points, {
    color: "green",
    weight: 1,
    dashArray: "5",
    opacity: 0.9,
    // pane: "shadowPane"
  });
  self.polyline24Marker = L.marker(L.latLng(28, 127), {
    icon: L.divIcon({
      iconSize: [21, 18],
      iconAnchor: [6, 20],
      className: "div-icon-bg",
      html:
        '<p style="white-space:normal;font-size:12px;font-weight: bolder;color:red;">' +
        "24小时警戒线" +
        "</p>",
    }),
  });
  self.polyline48Marker = L.marker(L.latLng(28, 132), {
    icon: L.divIcon({
      iconSize: [21, 18],
      iconAnchor: [6, 20],
      className: "div-icon-bg",
      html:
        '<p style="white-space:normal;font-size:12px;font-weight: bolder;color:green;">' +
        "48小时警戒线" +
        "</p>",
    }),
  });
};

/**添加警戒线(通用方法) */
Typhoon.prototype.addWarningLine = function () {
  let self = this;
  if (!self.map.hasLayer(self.polyline24)) {
    self.polyline24.addTo(self.map);
    self.polyline48.addTo(self.map);
    self.polyline24Marker.addTo(self.map);
    self.polyline48Marker.addTo(self.map);
  }
};

/**删除警戒线(通用方法) */
Typhoon.prototype.removeWarningLine = function () {
  let self = this;
  if (self.map.hasLayer(self.polyline24)) {
    self.map.removeLayer(self.polyline24);
    self.map.removeLayer(self.polyline48);
    self.map.removeLayer(self.polyline24Marker);
    self.map.removeLayer(self.polyline48Marker);
  }
};

/**抽稀重绘历史路径点(通用方法)*/
Typhoon.prototype.redrawHistoryPoint = function () {
  let self = this;
  if (self.isPopuping) {
    return;
  }
  for (let index = 0; index < self.typhoonIdArray.length; index++) {
    let TYPHOON_ID = self.typhoonIdArray[index];
    let tfdata_all = self.typhoonObjArray[TYPHOON_ID].tfdata_all;
    let newTfData = [];
    if (!tfdata_all) {
      continue;
    }
    self.typhoonObjArray[TYPHOON_ID].historyPointGroup.clearLayers();
    /**点图层数组 */
    let layers =
      self.typhoonObjArray[TYPHOON_ID].historyPointGroupHide.getLayers();
    //将折点抽稀重绘
    for (let i = 0; i < tfdata_all.length; i++) {
      let mydata = tfdata_all[i];
      let WD, JD;
      WD = mydata.lat;
      JD = mydata.lng;
      let posi = L.latLng(parseFloat(WD), parseFloat(JD));
      mydata.ContainerPoint = self.map.latLngToContainerPoint(posi);
      if (i === 0 || i === tfdata_all.length - 1) {
        newTfData.push(mydata);
        self.typhoonObjArray[TYPHOON_ID].historyPointGroup.addLayer(layers[i]);
      } else {
        let thisDis = mydata.ContainerPoint.distanceTo(
          newTfData[newTfData.length - 1].ContainerPoint
        );
        if (thisDis > 18) {
          newTfData.push(mydata);
          self.typhoonObjArray[TYPHOON_ID].historyPointGroup.addLayer(
            layers[i]
          );
        } else {
          continue;
        }
      }
    }
  }
};

/**按中心风级判断台风级别颜色(通用方法) */
Typhoon.prototype.setHistoryColor = function (power) {
  let self = this;
  let color = "";
  if (power <= 7) {
    //热带低压
    color = "rgba(2, 255, 2, 1)";
  } else if ((power > 7) & (power <= 9)) {
    //热带风暴
    color = "rgb(19, 98, 177)";
  } else if ((power > 9) & (power <= 11)) {
    //强热带风暴
    color = "rgba(255, 251, 5, 1)";
  } else if ((power > 11) & (power <= 13)) {
    //台风
    color = "rgba(255, 172, 5, 1)";
  } else if ((power > 13) & (power <= 15)) {
    //强台风
    color = "rgba(241, 113, 249, 1)";
  } else if (power > 15) {
    //超强台风
    color = "rgba(254, 2, 2, 1)";
  }
  return color;
};

/**按中心风级判断台风级别(通用方法) */
Typhoon.prototype.setHistoryPower = function (power) {
  power = parseInt(power);
  let _power = "";
  if (power <= 7) {
    //热带低压
    _power = "rddy";
  } else if ((power > 7) & (power <= 9)) {
    //热带风暴
    _power = "rdfb";
  } else if ((power > 9) & (power <= 11)) {
    //强热带风暴
    _power = "qrdfb";
  } else if ((power > 11) & (power <= 13)) {
    //台风
    _power = "tf";
  } else if ((power > 13) & (power <= 15)) {
    //强台风
    _power = "qtf";
  } else if (power > 15) {
    //超强台风
    _power = "cqtf";
  }
  return _power;
};

/**增加台风提示文本(通用方法)*/
Typhoon.prototype.addTyphoonPromptText = function (
  TYPHOON_ID,
  name,
  POWER,
  posiFinal
) {
  let self = this;
  let noTFObj = document.getElementById("typhoonText_" + "noTf");
  if (noTFObj) {
    document.getElementById("typhoonText").removeChild(noTFObj);
  }
  //201910罗莎(风力10级)
  let showText = TYPHOON_ID + name + "(风力" + POWER + "级)";
  let textDiv = document.createElement("div");
  textDiv.id = "typhoonText_" + TYPHOON_ID;
  textDiv.className = "promptTextStyle";
  textDiv.innerHTML = showText;
  let brObj = document.createElement("br");
  brObj.id = "typhoonBr_" + TYPHOON_ID;
  document.getElementById("typhoonText").appendChild(textDiv);
  document.getElementById("typhoonText").appendChild(brObj);
  textDiv.onclick = function () {
    $(".typhoonGif").hide();
    self.map.setView(posiFinal, 5);
    setTimeout(() => {
      $(".typhoonGif").show();
    }, 60);
    $(".typhoonPopupClose").click(); //关闭popup弹窗
  };
};

/**删除台风提示文本(通用方法)*/
Typhoon.prototype.removeTyphoonPromptText = function (TYPHOON_ID) {
  let self = this;
  let divObj = document.getElementById("typhoonText_" + TYPHOON_ID);
  let brObj = document.getElementById("typhoonBr_" + TYPHOON_ID);
  if (divObj) {
    document.getElementById("typhoonText").removeChild(divObj);
    document.getElementById("typhoonText").removeChild(brObj);
  }
};

/**台风风圈设置数据并绘制(通用方法)*/
Typhoon.prototype.TFcircleSetData = function (
  tfcircle,
  JD,
  WD,
  XXSE,
  XXSW,
  XXNW,
  XXNE
) {
  let self = this;

  //台风圆圈、圆心以及半径数据
  let circledata = [];
  circledata.push(parseFloat(JD));
  circledata.push(parseFloat(WD));
  circledata.push(parseFloat(XXSE));
  circledata.push(parseFloat(XXSW));
  circledata.push(parseFloat(XXNW));
  circledata.push(parseFloat(XXNE));
  let tftf = true;
  for (let i = 0; i < circledata.length; i++) {
    tftf = self.isNotANumber(circledata[i]);
    if (tftf === false) {
      break;
    }
  }
  if (tftf) {
    tfcircle.options.allowDraw = true;
    tfcircle._setdata(circledata, self.map);
  } else {
    tfcircle._clearcanvas();
    tfcircle.options.allowDraw = false;
  }
};

/**按预报台判断路径颜色(通用方法) */
Typhoon.prototype.setYbtColor = function (ybtName) {
  let self = this;
  let color = "";
  if (ybtName === "中国") {
    color = "rgba(255,60,78,0.9)";
  } else if (ybtName === "中国香港") {
    color = "rgba(255,0,254,0.9)";
  } else if (ybtName === "美国") {
    color = "rgba(4,250,247,1)";
  } else if (ybtName === "中国台湾") {
    color = "rgb(233, 156, 56)";
  } else if (ybtName === "日本") {
    color = "rgb(104, 235, 75)";
  } else if (ybtName === "韩国") {
    color = "rgba(62, 62, 65,0.8)";
  }
  return color;
};

/**判断是否是数字(通用方法)*/
Typhoon.prototype.isNotANumber = function (inputData) {
  //可以检查一个空字符串
  if (parseFloat(inputData).toString() == "NaN") {
    return false;
  } else {
    return true;
  }
};

/**转换时间字符串格式 */
Typhoon.prototype.formatTimeType = function (string) {
  //输入的时间字符串格式:2019-08-18T06:00:00
  let timeString1 = string.split("T")[0];
  let timeString2 = string.split("T")[1];
  let year = timeString1.split("-")[0];
  let month = timeString1.split("-")[1];
  let day = timeString1.split("-")[2];
  let hour = timeString2.split(":")[0];
  return year + "/" + month + "/" + day + " " + hour + ":00";
};

/**以公里数计算纬度增量返回风圈标注标注Marker */
Typhoon.prototype.calLngIncrement = function (dataFinal, se, sw, nw, ne, text) {
  // TODO: 绘制风圈标注
  let self = this;
  se = parseFloat(se);
  sw = parseFloat(sw);
  nw = parseFloat(nw);
  ne = parseFloat(ne);
  if (se > 0 || sw > 0 || nw > 0 || ne > 0) {
    let radius = nw > ne ? nw : ne;
    let posi = L.latLng(
      parseFloat(dataFinal.lat) + radius / 111.24,
      dataFinal.lng
    );
    let circle = text.substr(0, text.length - 3);
    /**风圈文字标注 */
    let textMarker = L.marker(posi, {
      icon: L.divIcon({
        iconSize: [0, 0],
        iconAnchor: [0, 0],
        className:
          "divIcon-typhoon-circle-textLabel divIcon-typhoon-circle" +
          circle +
          "-textLabel",
        html: '<div style="margin-left: -20px;">' + text + "</div>",
      }),
      zIndexOffset: 1,
    });
    return textMarker;
  } else {
    return null;
  }
};

/**创建popup内容 */
Typhoon.prototype.creatTyphoonPopupCont = function (jc) {
  let cont = $(
    '<div class="typhoonPopupContont"><div class="typhoonPopupTitle">' +
    jc.title +
    '<span class="typhoonPopupClose"></span></div></div>'
  );
  for (let i = 0; i < jc.cont.length; i++) {
    let ic = jc.cont[i];
    let isodd = i % 2 === 0 ? "odd" : "even";
    let d1 = $(
      '<div class="' +
      isodd +
      '"><table><tbody><tr><td class="typhoonPopupLabel"></td><td class="typhoonPopupValue"></td></tr></tbody></table></div>'
    );
    d1.find(".typhoonPopupLabel").text(ic.label);
    d1.find(".typhoonPopupValue").text(ic.value);
    cont.append(d1);
  }
  return cont[0].outerHTML;
};

/**深拷贝对象 */
Typhoon.prototype.deepCopyObj = function (obj) {
  var result = Array.isArray(obj) ? [] : {};
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      if (typeof obj[key] === "object" && obj[key] !== null) {
        result[key] = this.deepCopyObj(obj[key]); //递归复制
      } else {
        result[key] = obj[key];
      }
    }
  }
  return result;
};

//台风风圈图层
L.TFcirclelayer = L.Layer.extend({
  includes: L.Mixin.Events,
  options: {
    strokeStyle: "rgba(0,139,139,0.6)",
    fillStyle: "rgba(0,205,205,0.2)",
    allowDraw: false,
    showLabel: true,
    opacity: 1,
    weight: 0.8,
    zindex: 101,
  },
  initialize: function (options) {
    L.setOptions(this, options);
  },
  onAdd: function (map) {
    this._map = map;
    if (!this._container) {
      this._initCanvas();
    }
    map._panes.overlayPane.appendChild(this._container);
    map.on("zoomstart", this._clearcanvas, this);
    map.on("moveend", this._reset, this);
    if (map.options.zoomAnimation && L.Browser.any3d) {
      map.on("zoomanim", this._animateZoom, this);
    }
  },
  onRemove: function (map) {
    map.getPanes().overlayPane.removeChild(this._container);
    map.off("zoomstart", this._clearcanvas, this);
    map.off("moveend", this._reset, this);
    if (map.options.zoomAnimation) {
      map.off("zoomanim", this._animateZoom, this);
    }
  },
  addTo: function (map) {
    map.addLayer(this);
    return this;
  },
  bringToBack: function () {
    let pane = this._map._panes.overlayPane;
    if (this._canvas) {
      pane.insertBefore(this._canvas, pane.firstChild);
    }
    return this;
  },
  getAttribution: function () {
    return this.options.attribution;
  },
  _setZindex: function (Zindex) {
    this._container.style.zIndex = Zindex;
  },
  _initCanvas: function () {
    this._container = L.DomUtil.create("div", "leaflet-image-layer");
    this._canvas = L.DomUtil.create("canvas", "");
    this._canvas_label = L.DomUtil.create("canvas", "");
    this._setZindex(this.options.zindex);
    if (this._map.options.zoomAnimation && L.Browser.any3d) {
      L.DomUtil.addClass(this._canvas, "leaflet-zoom-animated");
      L.DomUtil.addClass(this._canvas_label, "leaflet-zoom-animated");
    } else {
      L.DomUtil.addClass(this._canvas, "leaflet-zoom-hide");
      L.DomUtil.addClass(this._canvas_label, "leaflet-zoom-animated");
    }
    this._container.appendChild(this._canvas);
    this._container.appendChild(this._canvas_label);
    L.extend(this._canvas, {
      onselectstart: L.Util.falseFn,
      onmousemove: L.Util.falseFn,
      onload: L.bind(this._onCanvasLoad, this),
    });
    L.extend(this._canvas_label, {
      onselectstart: L.Util.falseFn,
      onmousemove: L.Util.falseFn,
      onload: L.bind(this._onCanvasLoad, this),
    });
  },
  _animateZoom: function (e) {
    let map = this._map,
      container = this._container,
      canvas = this._canvas,
      scale = map.getZoomScale(e.zoom),
      nw = map.containerPointToLatLng([0, 0]),
      se = map.containerPointToLatLng([canvas.width, canvas.height]),
      topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
      size = map
        ._latLngToNewLayerPoint(se, e.zoom, e.center)
        ._subtract(topLeft),
      origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
  },
  _reset: function () {
    if (this.options.allowDraw) {
      let self = this;
      let container = this._container,
        canvas = this._canvas;
      if (!this._map) {
        return;
      }
      let size = this._map.getSize(),
        lt = this._map.containerPointToLayerPoint([0, 0]);
      L.DomUtil.setPosition(container, lt);
      this.width = size.x;
      this.height = size.y;
      container.style.width = size.x + "px";
      container.style.height = size.y + "px";
      canvas.style.width = size.x + "px";
      canvas.style.height = size.y + "px";
      canvas.width = size.x * 2;
      canvas.height = size.y * 2;
      self._beforedraw(this.ashuzu, this.amap);
    }
  },
  _onCanvasLoad: function () {
    this.fire("load");
  },
  _setdata: function (shuzu, map) {
    let self = this;
    self.ashuzu = shuzu;
    self.amap = map;
    self._reset();
  },
  _beforedraw: function (shuzu, map) {
    let self = this;
    let cenofcir = L.latLng(shuzu[1], shuzu[0]);
    let cenofcircontainer = map.latLngToContainerPoint(cenofcir);
    let rArray = [];
    //分别求取四个半径
    for (let i = 2; i < 6; i++) {
      let a1 = L.latLng(shuzu[1] + shuzu[i] / 111.24, shuzu[0]);
      let b1 = map.latLngToContainerPoint(a1);
      let r1 = self._distan(
        cenofcircontainer.x,
        cenofcircontainer.y,
        b1.x,
        b1.y
      );
      rArray.push(r1 * 2);
    }
    self.__draw(cenofcircontainer, rArray);
  },
  _distan: function (x1, y1, x2, y2) {
    let a1 = Math.pow(x1 - x2, 2);
    let a2 = Math.pow(y1 - y2, 2);
    return Math.sqrt(a1 + a2);
  },
  __draw: function (cenofcircontainer, rArray) {
    let self = this,
      canvas = this._canvas,
      map = this._map;
    cenofcircontainer.x = cenofcircontainer.x * 2;
    cenofcircontainer.y = cenofcircontainer.y * 2;
    if (L.Browser.canvas && map) {
      let Cwidth = canvas.clientWidth;
      let Cheight = canvas.clientHeight;
      let ctx = canvas.getContext("2d");
      ctx.clearRect(0, 0, Cwidth, Cheight);
      ctx.lineWidth = 2;
      ctx.strokeStyle = this.options.strokeStyle;

      //弧度//ctx.save();//ctx.restore();
      let startAngle = 0; //开始
      let endAngle = 0; //结束
      //先描边
      ctx.beginPath();
      ctx.moveTo(cenofcircontainer.x + rArray[0], cenofcircontainer.y);
      for (let i = 0; i < rArray.length; i++) {
        endAngle = endAngle + 0.25 * Math.PI * 2;
        ctx.arc(
          cenofcircontainer.x,
          cenofcircontainer.y,
          rArray[i],
          startAngle,
          endAngle,
          false
        );
        startAngle = endAngle;
      }
      ctx.closePath();
      ctx.stroke();
      //后填充
      endAngle = 0;
      for (let i = 0; i < rArray.length; i++) {
        endAngle = endAngle + 0.25 * Math.PI * 2;
        ctx.beginPath();
        ctx.moveTo(cenofcircontainer.x, cenofcircontainer.y);
        ctx.arc(
          cenofcircontainer.x,
          cenofcircontainer.y,
          rArray[i],
          startAngle,
          endAngle,
          false
        );
        ctx.closePath();
        ctx.fillStyle = this.options.fillStyle;
        ctx.fill();
        startAngle = endAngle;
      }
    }
  },
  _clearcanvas: function () {
    let self = this,
      canvas = this._canvas,
      map = this._map;
    if (L.Browser.canvas && map) {
      let Cwidth = canvas.clientWidth;
      let Cheight = canvas.clientHeight;
      let ctx = canvas.getContext("2d");
      ctx.clearRect(0, 0, Cwidth * 2, Cheight * 2);
    }
  },
  _latLngToCanvasPoint: function (latlng) {
    let map = this._map;
    let projectedPoint = map.project(L.latLng(latlng));
    projectedPoint._subtract(map.getPixelOrigin());
    return L.point(projectedPoint).add(map._getMapPanePos());
  },
});
L.tfcirclelayer = function (options) {
  return new L.TFcirclelayer(options);
};

let typhoon = new Typhoon();
export { typhoon };
// export default Typhoon
